package com.eascs.demand.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.item.service.O2oPubDdItemService;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.context.ConfigContext;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.demand.button.TicketButtonAll;
import com.eascs.demand.entity.MainApply;
import com.eascs.demand.entity.UserDemand;
import com.eascs.demand.service.DemandService;
import com.eascs.demand.service.TicketMainApplyService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.inject.Inject;
import java.util.*;
@Controller
public class TicketWorkFlowController extends BaseRestController{
	private static final Logger logger = LoggerFactory.getLogger(TicketWorkFlowController.class);
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Reference
	private WorkFlowService workFlowService;
	@Inject
	TicketButtonAll ticketButtonAll;
	@Inject
	TicketMainApplyService ticketMainApplyService;
	@Inject
	DemandService demandService;
	@Autowired
	BaseUtils baseUtils;
	@Autowired
	O2oPubDdItemService ddItemService;
	/**
	 * 需求申请 流程
	 * @author 唐洪全
	 * @return
	 */
	@RequestMapping("/demand/startup")
	public BaseRestResult<String> submitApply(String demandid) {
		MainApply mainApply = ticketMainApplyService.findMainApplyByExpandId(demandid);
		UserDemand demand = demandService.getUserDemandByBillcode(mainApply.getBillCode());
		logger.info("需求申请单号为：{}", mainApply.getBillCode());
		WFRequestParam param = new WFRequestParam();
		param.setReferId(mainApply.getMainapplyNo());
		param.setReferCode(mainApply.getBillCode());
		param.setReferUrl(ConfigContext.getStringValue("o2o.demand.approvalUrl")+"&mainapplyNo="+mainApply.getMainapplyNo());
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		String demandType = demand.getDemandType();
		//如果是系统需求申请：系统错误、系统咨询、单据修改、其它
		String itemtype=ddItemService.findPubdditemO2ONameByCode("SYSDEMANDTYPE", demandType);
		if("SYSERR".equals(demandType) || "XTZX".equals(demandType) || "DJXG".equals(demandType) || "OTH".equals(demandType) || "EXDATA".equals(demandType)){
			param.setProcessType(ProcessTemplate.PROECESS_TYPE_REQUIREMENT_APP);
			if ("SYSERR".equals(demandType) || "XTZX".equals(demandType) || "DJXG".equals(demandType) || "OTH".equals(demandType)) {
				List<String> deleteParmList=new ArrayList<String>();
				deleteParmList.add("O2OCEO");
				param.setExcludeNodeCodeList(deleteParmList);
			}
		}else if("QXCL".equals(demandType) || "GNBG".equals(demandType) || "MBI".equals(demandType)){
			//如果是业务需求申请：权限处理，功能新增/变更/建议，基础信息维护
			param.setProcessType(ProcessTemplate.PROECESS_TYPE_BUS_REQUIREMENT_APP);
			List<String> deleteParmList=new ArrayList<String>();
			if (!"QXCL".equals(demandType)) {
				deleteParmList.add("node_hrfzr");
			}
			param.setExcludeNodeCodeList(deleteParmList);
		}else if("DJZF".equals(demandType)){
			//如果是需求申请（只需要过总部领导的）:作废
			param.setProcessType(ProcessTemplate.PROECESS_TYPE_HQ_REQUIREMENT_APP);
		}else if("SYSDEVELOP".equals(demandType)){
			//如果是系统开发
			param.setProcessType(ProcessTemplate.PROECESS_TYPE_SYSTEM_DEV);
		}else if (!StringUtils.isEmpty(itemtype)) {
			param.setProcessType(demandType);
		}
		param.setProcessVersion("v1");
		param.setAppliedby(demand.getDemandUserid());
		//param.setAppliedbyName(mainApply.getCreator());//
		param.setAppliedbyName("申请人：" + demand.getDemandUser());
		Map<String, List<String>> roleUserMap = new HashMap<>();  //指定流程节点由谁经办
		roleUserMap.put(StatusContexts.LOAN_TYPE_PTJL_ROLE, Arrays.asList(mainApply.getOperatorNo()));  //最后一个节点，动态指定经办人
		//如果提交人是总部的人，省区负责人设置为自己
		if("24793".equals(mainApply.getLtd())){
			roleUserMap.put(StatusContexts.LOAN_TYPE_JRZJ_ROLE, Arrays.asList(mainApply.getOperatorNo()));
		}
		param.setRoleUserMap(roleUserMap);
		param.setOrgNo(mainApply.getLtd());
		//摘要
		param.setAppliedDes("需求申请：" + demand.getTitle());
//		logger.debug("提交面签申报，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
//				loan.getLoanapplyNo(),loan.getBillCode(),ProcessTemplate.SYSTEM_MODULE_O2O,param.getProcessType(),loan.getLtd(),appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			logger.info("提交需求申请工作流成功，单号：{}，返回对象：{}", mainApply.getMainapplyNo(), modelResult.getModel().toString());
			ticketMainApplyService.updateWorkFlowStatus(StatusContexts.WFTYPE_STATUS_RUN, mainApply.getMainapplyNo());
			return BaseRestResult.info("提交成功").andRefresh();
		} else {
			logger.error("需求申请 流程启动失败，错误信息{}", modelResult.getDetailStack());
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
	}
	
	
	/**
	 * 
	 * 代办审批列表 详情页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/demand/approval")
	public HtmlRestResult approval(String referId, String nodeAuditorId, String approvalStatus) {
		String approvalUrl = baseUtils.getApprovalUrl(nodeAuditorId, ProcessTemplate.SYSTEM_MODULE_O2O);// 审批代办列表详情URL
		String agreeUrl = baseUtils.getApprovalAgreeUrl(referId, nodeAuditorId, ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("approvalUrl", approvalUrl);
		
		UserDemand userDemand = demandService.getUserDemandByBillcode(ticketMainApplyService.findMainApplyById(referId).getBillCode());
		ViewContext.put("approvalStatus", approvalStatus);//流程经办状态是待办/已办/已发起，待办状态才显示审批栏
		ViewContext.put("datalistInfo",getDatalistInfo(userDemand.getBillCode()));
		ViewContext.put("userDemand", userDemand);
		
		return HtmlRestResult.popHtmlFragment("/demand/approval");
	}
	
	/**
	 * 附件列表
	 * @return
	 */
	public PaginationInfo getDatalistInfo(String demandNo){
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(demandNo);
		String titles[] = {"附件类型","文件名", "提交人", "提交时间","更新时间"};
		Button[] titleButtons = new Button[] {null,ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo datalistInfo = new PaginationInfo(pageResult, titles, "/loanUser/loanudpate");
		datalistInfo.setTitleButtons(titleButtons);
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(1);
		datalistInfo.setBuildRowNumber(true);
		return datalistInfo;
	}
	
	
	@RequestMapping(value = "/demand/loan-detail-button", method = RequestMethod.GET)
	public HtmlRestResult loanDetailButton(String demandid) {
		List<Button> buttons = ticketButtonAll.buildButtons(demandid);
		ViewContext.put("buttons", buttons);
		return new HtmlRestResult("/demand/loanDetailButton");
	}
}
